package com.ai.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.ai.web.cache.Constants;
import com.ai.web.cache.UserContext;
import com.ai.web.service.LoginOutService;
import com.ai.web.util.MD5Util;
import com.tiny.persistence.domain.BgUser;

@Controller
@RequestMapping("/login")
@SessionAttributes(Constants.USER_CONTEXT)
public class LoginController extends BaseController {

	private static Logger logger = Logger.getLogger(LoginController.class);

	@Autowired
	private LoginOutService loginOutService;

	@ResponseBody
	@RequestMapping(value = "/in")
	public Map<String, Object> login(HttpServletRequest request,
			@RequestParam String username, @RequestParam String password,
			ModelMap model,
			@CookieValue(value = "pageSize", required = false) Integer pageSize) {
		Map<String, Object> dataMap = new HashMap<String, Object>();

		logger.info("login user=" + username + " password=" + password);
		BgUser authUser = loginOutService.getBgUser(username);
		logger.info("authUser=" + authUser);
		if (authUser != null) {
			String dbPassWord = authUser.getPassword();
			try {
				boolean valiPass = MD5Util.validPassword(password, dbPassWord);
				if (valiPass) {
					if (pageSize == null || pageSize <= 0) {
						pageSize = Constants.DEFAULT_PAGE_SIZE;

						setCookie("pageSize", pageSize);
					}
					UserContext uc = new UserContext();
					uc.setBgUser(authUser);
					uc.setPageSize(pageSize);
					model.addAttribute(Constants.USER_CONTEXT, uc);
					dataMap.put("result", true);
					dataMap.put("url", "main");
				} else {
					dataMap.put("result", false);
					dataMap.put("msg", "用户名或者密码不正确!");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			dataMap.put("result", false);
			dataMap.put("msg", "用户名不存在!");
		}
		return dataMap;
	}

	@RequestMapping(value = "/out")
	public String logout(SessionStatus status) {

		status.setComplete();
		return "redirect:/index.jsp";
	}

}
